package com.linln.wxapi;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.linln.common.constant.NoticeTypeConst;
import com.linln.common.utils.MoneyUtils;
import com.linln.modules.ad.service.AdInfoService;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberAgentMoneyChange;
import com.linln.modules.member.domain.MemberOrder;
import com.linln.modules.member.repository.MemberAgentMoneyChangeRepository;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberOrderService;
import com.linln.modules.member.service.MemberRefundService;
import com.linln.modules.message.service.MessageInfoService;
import com.linln.modules.store.service.StoreinfoService;
import com.linln.wxapi.config.WeChatPayProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * @author : Gentle
 * @date : 2019/5/17 12:38
 * @description:
 */
@RestController
@RequestMapping(value = "/wx")
@Slf4j
public class WeChatNoticeController {

    private static final String REFUND_SUCCESS = "SUCCESS";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    WeChatPayProperties weChatPayProperties;
  
    @Autowired
    private  MessageInfoService messageInfoService;

    @Autowired
    private  StoreinfoService storeService;

    @Autowired
    private  AdInfoService adService;

 
    @Autowired
    private  MemberAgentService memberAgentService;
    @Autowired
    private  MemberOrderService orderService;
    
    @Autowired
    private  MemberRefundService refundService;
    @Autowired
    private MemberAgentMoneyChangeRepository changeRepository;

    /**
    *
    * @param xmlData 微信返回的流
    * @return
    */
   @RequestMapping(value = "/notify",method = {RequestMethod.GET,RequestMethod.POST})
   public String weChatNotify(@RequestBody String xmlData){

       try {
    	   
           System.out.println("我进入了支付以后消息通知的地方：===============================================");
           System.out.println(xmlData);

           final WxPayOrderNotifyResult notifyResult = this.wxPayService.parseOrderNotifyResult(xmlData);
           //这里是存储我们发起支付时订单号的信息，所以取出来
           notifyResult.getOutTradeNo();
             /**
             * 系统内部业务，修改订单状态之类的
                                       支付成功后将信息放入订单表
                                       resultCode=FAIL, errCode=ORDERPAID
            */
          if(notifyResult.getReturnCode().equals("SUCCESS")) {
        	  if(notifyResult.getResultCode().equals("SUCCESS") || (
        			  notifyResult.getResultCode().equals("FAIL") && notifyResult.getErrCode().equals("ORDERPAID"))){
        		  MemberOrder order= orderService.findByOrderCode(notifyResult.getOutTradeNo());
        		  //钱直接进入代理商账户
                  if(order!=null && order.getId()>0) {        	  
           	         if(orderService.updatePayStatus(notifyResult.getOutTradeNo())>0) {
           	        	if(order.getType()!=5) {
           	        		try {
           	        		MemberAgentMoneyChange change=new MemberAgentMoneyChange();
           	        		MemberAgent agent=memberAgentService.getByArea(order.getArea());
           	        		change.setArea(order.getArea());
           	        		change.setChangemoney(order.getMoney());
           	        		change.setPreMoney(agent.getCurmoney());
           	        		change.setLastmoney(MoneyUtils.add(agent.getCurmoney(),order.getMoney()));
           	        		change.setCreateDate(order.getCreateDate());
           	        		change.setUpdateDate(order.getCreateDate());
           	        		change.setStatetype(1);
           	        		change.setStatus(1);           	        		
           	        		changeRepository.save(change);
           	        		System.out.println("添加详情记录"); 

           	        		}catch(Exception e) {
               	        		System.out.println("添加详情记录异常");
                                logger.info("添加详情记录异常");
                                e.getStackTrace();
           	        		}
                      	    //状态变化成功
           	        		System.out.println("消息付款回调--》增加给代理商回调"+order.getMoney()+">>>>>>>"+ order.getArea()); 
                      	    memberAgentService.addMoney(order.getMoney(), order.getArea());
                        }
           	         }
                      if(order.getType()==NoticeTypeConst.MESSAGE) {
                    	  System.out.println("消息付费回调");
                   	      messageInfoService.updatePayStatus(notifyResult.getOutTradeNo());                  	  
                      }else if(order.getType()==NoticeTypeConst.STORE) {
                    	  System.out.println("商户付费回调");
                   	      storeService.updatePayStatus(notifyResult.getOutTradeNo());
                      }else if(order.getType()==NoticeTypeConst.AD) {
                    	  System.out.println("广告付费回调");
                   	      adService.updatePayStatus(notifyResult.getOutTradeNo());
                      }else if(order.getType()==NoticeTypeConst.AGENT){
                    	  System.out.println("代理商付费回调");
                    	  memberAgentService.updatePayStatus(notifyResult.getOutTradeNo());                    	  
                      }
                      
                      //要发送小程序模板消息给客户
                      //1,配置小程序信息
                      //WxMaConfiguration wxConfig=WxMaConfiguration.getMaService(appid);
                      //WxMaConfig wxConfig=new WxMaDefaultConfigImpl();
                      /*WxMaService wxMaService = WxMaConfiguration.getMaService(ConstUtil.appid);
                      //2,设置模版信息（keyword1：类型，keyword2：内容）
                      List<WxMaTemplateData> templateDataList = new ArrayList<>(2);
                      WxMaTemplateData data1 = new WxMaTemplateData("keyword1", order.getOrderCode());
                      WxMaTemplateData data2 = new WxMaTemplateData("keyword2", "置顶服务费");
                      WxMaTemplateData data3 = new WxMaTemplateData("keyword3", order.getMoney()+"");
                      WxMaTemplateData data4 = new WxMaTemplateData("keyword4", order.getContent());
                      WxMaTemplateData data5 = new WxMaTemplateData("keyword5", DateUtils.formatDate(order.getCreateDate()));
                      
                      templateDataList.add(data1);
                      templateDataList.add(data2);
                      templateDataList.add(data3);
                      templateDataList.add(data4);
                      templateDataList.add(data5);
                      System.out.println("order.getPrepay_id()======="+order.getPrepay_id());
        */
                      //3，设置推送消息
                      /*WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder()
                              .toUser(order.getMember().getOpenid())//要推送的用户openid
                              .formId(order.getPrepay_id())//收集到的formid
                              //.templateId("eqc9VidnbKLhMcFPcE4SbaRkqlRQkOLYHUm73QOd0Uw")//推送的模版id（在小程序后台设置）
                              .templateId("4QIM0S1qHU05wksGez6WnEntHz-XBC0_3v7A81_xC94")//推送的模版id（在小程序后台设置）
                              
                              .data(templateDataList)//模版信息
                              .page("pages/index/index")//要跳转到小程序那个页面
                              .build();*/
                      //4，发起推送
                      /*try {
                    	  wxMaService.getMsgService().sendTemplateMsg(templateMessage);
                      } catch (WxErrorException e) {
                          System.out.println("推送失败：" + e.getMessage());
                          //return e.getMessage();
                      }*/
                     // return "推送成功";
                  }
        	  }else {
        		  
        	  }
          }
          
          //成功后回调微信信息
           return WxPayNotifyResponse.success("回调成功！");
       } catch (WxPayException e) {
           e.printStackTrace();
           return WxPayNotifyResponse.fail("回调有误!");
       }
   }
    /**
     * 仅支持一次性退款，多次退款需要修改逻辑
     * @param xmlData 微信返回的流数据
     * @return
     */
    @RequestMapping(value = "/refundNotify",method = {RequestMethod.GET,RequestMethod.POST})
    public String refundNotify(@RequestBody String xmlData) {
        System.out.println("我进入了退款以后消息通知的地方：");
        WxPayRefundNotifyResult wxPayRefundNotifyResult;
        try {
            wxPayRefundNotifyResult = wxPayService.parseRefundNotifyResult(xmlData);
        } catch (WxPayException e) {
            log.error("退款失败，失败信息:{}", e);
            return WxPayNotifyResponse.fail("退款失败");
        }
        //判断你返回状态信息是否正确
        if (REFUND_SUCCESS.equals(wxPayRefundNotifyResult.getReturnCode())) {
            WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
            //判断退款状态
            if (REFUND_SUCCESS.equals(reqInfo.getRefundStatus())) {
                //内部订单号
                String outTradeNo = reqInfo.getOutTradeNo();

                MemberOrder order= orderService.findByOrderCode(outTradeNo);
                
                if(order!=null && order.getId()>0) {
                	System.out.println("退款回调信息"); 
                	memberAgentService.decMoney(order.getMoney(), order.getArea());
                	refundService.updateRefundStatus(outTradeNo);
                	orderService.updateRefundStatus(outTradeNo);
                    if(order.getType()==NoticeTypeConst.MESSAGE) {
                 	   messageInfoService.updateRefundStatus(outTradeNo);                 	   
                    }else if(order.getType()==NoticeTypeConst.STORE) {
                 	   storeService.updateRefundStatus(outTradeNo);
                    }else if(order.getType()==NoticeTypeConst.AD) {
                 	   adService.updateRefundStatus(outTradeNo);
                    }else if(order.getType()==NoticeTypeConst.AGENT){
                  	  System.out.println("代理商付费回调");
                  	  memberAgentService.updateRefundStatus(outTradeNo);
                    }      
                }
                
                
                return WxPayNotifyResponse.success("退款成功！");
            }
        }

        return WxPayNotifyResponse.fail("回调有误!");
    }

    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }





    /**
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/notify_",method = {RequestMethod.GET,RequestMethod.POST})
    public String weChatNotify_(String orderNo){

        try {
                    MemberOrder order= orderService.findByOrderCode(orderNo);
                    //钱直接进入代理商账户
                    if(order!=null && order.getId()>0) {
                        if(orderService.updatePayStatus(orderNo)>0) {
                            if(order.getType()!=5) {
                                try {
                                    MemberAgentMoneyChange change=new MemberAgentMoneyChange();
                                    MemberAgent agent=memberAgentService.getByArea(order.getArea());//.getByMemberIdAndArea(order.getMember().getId(),order.getArea());
                                    change.setArea(order.getArea());
                                    change.setChangemoney(order.getMoney());
                                    change.setPreMoney(agent.getCurmoney());
                                    change.setLastmoney(MoneyUtils.add(agent.getCurmoney(),order.getMoney()));
                                    change.setCreateDate(order.getCreateDate());
                                    change.setUpdateDate(order.getCreateDate());
                                    change.setStatetype(1);
                                    change.setStatus(1);
                                    changeRepository.save(change);
                                    System.out.println("添加详情记录");

                                }catch(Exception e) {
                                    System.out.println("添加详情记录异常");
                                }
                                //状态变化成功
                                System.out.println("消息付款回调--》增加给代理商回调"+order.getMoney()+">>>>>>>"+ order.getArea());
                   //             memberAgentService.addMoney(order.getMoney(), order.getArea());
                            }
                        }
                       /* if(order.getType()==NoticeTypeConst.MESSAGE) {
                            System.out.println("消息付费回调");
                            messageInfoService.updatePayStatus(orderNo);
                        }else if(order.getType()==NoticeTypeConst.STORE) {
                            System.out.println("商户付费回调");
                            storeService.updatePayStatus(orderNo);
                        }else if(order.getType()==NoticeTypeConst.AD) {
                            System.out.println("广告付费回调");
                            adService.updatePayStatus(orderNo);
                        }else if(order.getType()==NoticeTypeConst.AGENT){
                            System.out.println("代理商付费回调");
                            memberAgentService.updatePayStatus(orderNo);
                        }*/
                    }
            return WxPayNotifyResponse.success("回调成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail("回调有误!");
        }
    }

}